package com.blog.blog.service.oss.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ListObjectsRequest;
import com.blog.blog.config.SiteProperties;
import com.blog.blog.service.oss.OssService;
import com.blog.blog.vo.OssFileVO;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class AliyunOssService implements OssService {

    private final SiteProperties siteProperties;

    public AliyunOssService(SiteProperties siteProperties) {
        this.siteProperties = siteProperties;
    }

    private OSS client() {
        return new OSSClientBuilder().build(
                siteProperties.getOssEndpoint(),
                siteProperties.getOssAccessKeyId(),
                siteProperties.getOssAccessKeySecret()
        );
    }

    @Override
    public OssFileVO upload(byte[] data, String objectKey, String contentType) {
        OSS oss = client();
        try {
            ObjectMetadata meta = new ObjectMetadata();
            if (contentType != null) meta.setContentType(contentType);
            oss.putObject(siteProperties.getOssBucket(), objectKey, new java.io.ByteArrayInputStream(data), meta);
        } finally {
            if (oss != null) {
                try { oss.shutdown(); } catch (Exception ignored) {}
            }
        }
        String urlBase = siteProperties.getOssPublicBaseUrl();
        if (urlBase == null || urlBase.isBlank()) {
            urlBase = String.format("https://%s.%s", siteProperties.getOssBucket(), siteProperties.getOssEndpoint().replaceFirst("^https?://", ""));
        }
        OssFileVO vo = new OssFileVO();
        vo.setKey(objectKey);
        vo.setUrl(urlBase.replaceAll("/$", "") + "/" + objectKey);
        return vo;
    }

    @Override
    public void delete(String objectKey) {
        OSS oss = client();
        try {
            oss.deleteObject(siteProperties.getOssBucket(), objectKey);
        } finally {
            if (oss != null) {
                try { oss.shutdown(); } catch (Exception ignored) {}
            }
        }
    }

    @Override
    public boolean exists(String objectKey) {
        OSS oss = client();
        try {
            return oss.doesObjectExist(siteProperties.getOssBucket(), objectKey);
        } finally {
            if (oss != null) {
                try { oss.shutdown(); } catch (Exception ignored) {}
            }
        }
    }
    
    @Override
    public byte[] download(String objectKey) {
        OSS oss = client();
        try {
            InputStream inputStream = oss.getObject(siteProperties.getOssBucket(), objectKey).getObjectContent();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            return outputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("下载OSS文件失败: " + objectKey, e);
        } finally {
            if (oss != null) {
                try { oss.shutdown(); } catch (Exception ignored) {}
            }
        }
    }
    
    @Override
    public List<OssFileVO> listObjects(String prefix) {
        OSS oss = client();
        try {
            ListObjectsRequest request = new ListObjectsRequest(siteProperties.getOssBucket());
            request.setPrefix(prefix);
            request.setMaxKeys(1000); // 最多返回1000个对象
            
            ObjectListing objectListing = oss.listObjects(request);
            List<OssFileVO> result = new ArrayList<>();
            
            String urlBase = siteProperties.getOssPublicBaseUrl();
            if (urlBase == null || urlBase.isBlank()) {
                urlBase = String.format("https://%s.%s", siteProperties.getOssBucket(), siteProperties.getOssEndpoint().replaceFirst("^https?://", ""));
            }
            
            for (OSSObjectSummary summary : objectListing.getObjectSummaries()) {
                OssFileVO vo = new OssFileVO();
                vo.setKey(summary.getKey());
                vo.setUrl(urlBase.replaceAll("/$", "") + "/" + summary.getKey());
                vo.setSize(summary.getSize());
                vo.setLastModified(summary.getLastModified());
                result.add(vo);
            }
            
            return result;
        } finally {
            if (oss != null) {
                try { oss.shutdown(); } catch (Exception ignored) {}
            }
        }
    }
}


